// oss 富文本
import React from 'react';
import { observer } from 'mobx-react-lite';
import BraftEditor, { BraftEditorProps } from 'braft-editor';
import { PictureOutlined } from '@ant-design/icons';
import { config } from '~/config/config';

interface Props extends Omit<BraftEditorProps, 'value' | 'onChange'>{
  value: BraftEditorProps['value']
  onChange?: BraftEditorProps['onChange']
}

export const RichText = observer((props: Props) => {
  const {
    value,
    onChange,
  } = props;

  // 自定义图片转换形式  默认base64，定义为oss上传
  const myUploadFn = (param: any) => {
    const serverURL = `${config.remoteUrl}/file/oss_upload`;
    const xhr = new XMLHttpRequest();
    xhr.withCredentials = true;
    const fd = new FormData();

    const successFn = () => {
      // 假设服务端直接返回文件上传后的地址
      // 上传成功后调用param.success并传入上传后的文件地址
      let pictureUrl = '';
      const responseText: any = JSON.parse(xhr.responseText);
      if (responseText && responseText.code === 200) {
        pictureUrl = (responseText.file_prefix as string) + (responseText.data as string);
      }
      param.success({
        url: pictureUrl,
      });
    };

    const progressFn = (event: any) => {
      // 上传进度发生变化时调用param.progress
      // eslint-disable-next-line no-mixed-operators
      param.progress(event.loaded / event.total * 100);
    };

    const errorFn = () => {
      // 上传发生错误时调用param.error
      param.error({
        msg: 'unable to upload.',
      });
    };

    xhr.upload.addEventListener('progress', progressFn, false);
    xhr.addEventListener('load', successFn, false);
    xhr.addEventListener('error', errorFn, false);
    xhr.addEventListener('abort', errorFn, false);
    fd.append('file', param.file);
    xhr.open('POST', serverURL, true);
    xhr.send(fd);
  };

  // 指定编辑器工具栏的控件列表
  const controlOrigin = [
    'undo', 'redo', 'separator',
    'font-size', 'line-height', 'letter-spacing', 'separator',
    'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator',
    'superscript', 'subscript', 'remove-styles', 'emoji', 'separator', 'text-indent', 'text-align', 'separator',
    'headings', 'list-ul', 'list-ol', 'blockquote', 'code', 'separator',
    'link', 'separator', 'hr', 'separator',
    'media', 'separator',
    'clear',
  ];

  const controls = controlOrigin.map((item: any) => (item === 'media' ? {
    key: 'media', // 使用key来指定控件类型
    title: 'Insert the picture', // 自定义控件title
    text: <PictureOutlined/>, // 使用自定义文案来代替默认图标(B)，此处也可传入jsx
  } : item));


  const handleChange = (editorState: any) => {
    if (onChange) onChange(editorState);
  };

  return (
    <div>
      <BraftEditor
        value={value}
        onChange={handleChange}
        language="en"
        media={{
          uploadFn: myUploadFn,
          accepts: {
            image: 'image/png,image/jpeg,image/gif,image/webp,image/apng,image/svg',
            video: false,
            audio: false,
          },
          externals: {
            image: false,
            video: false,
            audio: false,
            embed: false,
          },
        }}
        controls={controls}
      />
    </div>
  );
});
